package club.lovety.es.service;

import club.lovety.es.client.ESClientUtils;
import club.lovety.es.model.UserInfo;
import club.lovety.es.mybatis.UserMapper;
import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 这里写文档描述
 *
 * @author smc
 * @date 2018-08-29 10:46
 * @since
 */
@Service
public class CommonService {

    private static final Logger log = LoggerFactory.getLogger(CommonService.class);

    @Resource
    private UserMapper userMapper;

    public String createIndex(UserInfo user) {
        Client client = ESClientUtils.getClient();
        CreateIndexRequest createIndexRequest = new CreateIndexRequest();
        IndexResponse indexResponse = client.prepareIndex("user_db", "person", String.valueOf(user.getId())).setSource(JSON.toJSONString(user), XContentType.JSON).get();
        DocWriteResponse.Result result = indexResponse.getResult();
        log.info("result: {}", result);
        return result.toString();
    }

    public void createUserES() {
        List<Map<String, Object>> list = userMapper.queryList();
        Client client = ESClientUtils.getClient();
        list.forEach(map -> {
            log.info("user_id: {}", map.get("user_id"));
            client.prepareIndex("user_db", "nacha_user", String.valueOf(map.get("user_id"))).setSource(map).get();
            log.info("创建成功");
        });
    }

    public void createLogES(){
        List<Map<String,Object>> list = userMapper.queryLog();
        Client client = ESClientUtils.getClient();
        list.forEach(map -> {
            log.info("user_id: {}", map.get("id"));
            client.prepareIndex("log", "user_log", String.valueOf(map.get("id"))).setSource(map).get();
            log.info("创建成功");
        });
    }

}
